package org.jeecg.modules.assets.controller;

import java.text.ParseException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.assets.dto.StartAssetsDTO;
import org.jeecg.modules.assets.entity.AssetsPreliminaryResults;
import org.jeecg.modules.assets.entity.AssetsPreliminaryResultsItem;
import org.jeecg.modules.assets.service.IAssetsItemService;
import org.jeecg.modules.assets.service.IAssetsPreliminaryResultsService;

import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 初盘结果管理
 * @Author: jeecg-boot
 * @Date: 2023-12-12
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "初盘结果管理")
@RestController
@RequestMapping("/assets/assetsPreliminaryResults")
public class AssetsPreliminaryResultsController extends JeecgController<AssetsPreliminaryResults, IAssetsPreliminaryResultsService> {
    @Autowired
    private IAssetsPreliminaryResultsService assetsPreliminaryResultsService;

    @Autowired
    private ISysBaseAPI iSysBaseAPI;
    @Autowired
    private IAssetsItemService assetsItemService;

    /**
     * 分页列表查询
     *
     * @param assetsPreliminaryResults
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "初盘结果管理-分页列表查询")
    @ApiOperation(value = "初盘结果管理-分页列表查询", notes = "初盘结果管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(AssetsPreliminaryResults assetsPreliminaryResults,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        String startTime = assetsPreliminaryResults.getStartTime();
        assetsPreliminaryResults.setStartTime(null);
      if(   pageSize==100){
          pageSize=9999;
      }
        QueryWrapper<AssetsPreliminaryResults> queryWrapper = QueryGenerator.initQueryWrapper(assetsPreliminaryResults, req.getParameterMap());
        Page<AssetsPreliminaryResults> page = new Page<AssetsPreliminaryResults>(pageNo, pageSize);
        if(StringUtils.isNotEmpty(startTime)){
            queryWrapper.eq("DATE_FORMAT(start_time, '%Y-%m')",startTime);
        }
        if(StringUtils.isNotEmpty( assetsPreliminaryResults.getCompany())){
        queryWrapper.exists("SELECT 1 from  assets_preliminary_results_item b WHERE  assets_preliminary_results.id =b.apply_id and b.company={0}",assetsPreliminaryResults.getCompany());
        }
        queryWrapper.orderByDesc("start_time");
        IPage<AssetsPreliminaryResults> pageList = assetsPreliminaryResultsService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param assetsPreliminaryResults
     * @return
     */
    @AutoLog(value = "初盘结果管理-添加")
    @ApiOperation(value = "初盘结果管理-添加", notes = "初盘结果管理-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AssetsPreliminaryResults assetsPreliminaryResults) {
        assetsPreliminaryResultsService.save(assetsPreliminaryResults);
        return Result.OK("添加成功！");
    }


    /**
     * 编辑
     *
     * @param assetsPreliminaryResults
     * @return
     */
    @AutoLog(value = "初盘结果管理-编辑")
    @ApiOperation(value = "初盘结果管理-编辑", notes = "初盘结果管理-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<?> edit(@RequestBody AssetsPreliminaryResults assetsPreliminaryResults) {
        assetsPreliminaryResultsService.updateById(assetsPreliminaryResults);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "初盘结果管理-通过id删除")
    @ApiOperation(value = "初盘结果管理-通过id删除", notes = "初盘结果管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        assetsPreliminaryResultsService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 发起盘点任务
     */
    @AutoLog(value = "初盘结果管理-发起盘点")
    @ApiOperation(value = "初盘结果管理-发起盘点", notes = "初盘结果管理-发起盘点")
    @RequestMapping(value = "/startAssetsJob", method = RequestMethod.POST)
    public Result<?> startAssetsJob() {
        assetsPreliminaryResultsService.startAssetsJob();
        return Result.OK("发起盘点成功！");
    }
    /**
     * 添加
     *
     * @param
     * @return
     */
    @AutoLog(value = "初盘结果管理-创建")
    @ApiOperation(value="初盘结果管理-创建", notes="初盘结果管理-创建")
    @PostMapping(value = "/startAssets")
    public Result<?> startAssets(@RequestBody StartAssetsDTO startAssets) throws ParseException {
        //获取资产明细中所有的资产
        //todo
        List<String> companyCodeList = assetsItemService.getAllCompanyCode();
        //将资产明细中的公司和选中公司对比
        if(StringUtils.isNotEmpty(startAssets.getCompany())){
            String[] companys = startAssets.getCompany().split(",");
            for (int i = 0; i < companys.length; i++) {
                if(!companyCodeList.contains(companys[i])) {
                    return Result.error("公司代码"+companys[i]+"资产未同步，请sap同步后再创建！");
                }
            }

        }
        ThreadUtil.execAsync(() -> {
            try {
                assetsPreliminaryResultsService.startAssets(startAssets);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        });

        return Result.OK("添加成功！");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "初盘结果管理-批量删除")
    @ApiOperation(value = "初盘结果管理-批量删除", notes = "初盘结果管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.assetsPreliminaryResultsService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "初盘结果管理-通过id查询")
    @ApiOperation(value = "初盘结果管理-通过id查询", notes = "初盘结果管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        AssetsPreliminaryResults assetsPreliminaryResults = assetsPreliminaryResultsService.getById(id);
        return Result.OK(assetsPreliminaryResults);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param assetsPreliminaryResults
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AssetsPreliminaryResults assetsPreliminaryResults) {
        return super.exportXls(request, assetsPreliminaryResults, AssetsPreliminaryResults.class, "初盘结果管理");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AssetsPreliminaryResults.class);
    }

}
